package com.cskaoyan.user.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cskaoyan.mall.commons.result.ResponseData;
import com.cskaoyan.mall.commons.result.ResponseUtil;
import com.cskaoyan.mall.commons.util.CookieUtil;
import com.cskaoyan.mall.commons.util.jwt.JwtTokenUtils;
import com.cskaoyan.user.constants.UserRetCode;
import com.cskaoyan.user.dto.UserDto;
import com.cskaoyan.user.dto.UserLoginResponse;
import com.cskaoyan.user.form.KaptchaCodeRequest;
import com.cskaoyan.user.form.UserLoginRequest;
import com.cskaoyan.user.form.UserRegisterRequest;
import com.cskaoyan.user.form.UserVerifyRequest;
import com.cskaoyan.user.service.IKaptchaService;
import com.cskaoyan.user.service.ILoginService;
import com.cskaoyan.user.service.IUserRegisterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.io.IOException;
import java.util.HashMap;

@Controller
@RequestMapping("user")
@ResponseBody
public class UserController {

    @Autowired
    IKaptchaService iKaptchaService;
    @Autowired
    ILoginService iLoginService;
    @Autowired
    IUserRegisterService iUserRegisterService;

    /**
     * 请求路径：/user/login
     * 是否需要携带Token：否
     * 请求类型：post
     * 请求参数示例：
     * {"userName":"test","userPwd":"test","captcha":"wbqj"}
     *
     * @return
     */
    @PostMapping("login")
    public ResponseData login(@RequestBody UserLoginRequest loginRequest, HttpServletRequest request, HttpServletResponse response) {
//        String userName = map.get("userName");
//        String userPwd = map.get("userPwd");
//        String captcha = map.get("captcha");

        //验证验证码是否正确
        KaptchaCodeRequest kaptchaCodeRequest = new KaptchaCodeRequest();
        kaptchaCodeRequest.setCode(loginRequest.getCaptcha());
        String uuid = CookieUtil.getCookieValue(request, "kaptcha_uuid");
        kaptchaCodeRequest.setUuid(uuid);
        iKaptchaService.validateKaptchaCode(kaptchaCodeRequest);
        //验证账号密码是否正确
        UserLoginResponse login = iLoginService.login(loginRequest);
        if (login == null) {
            return new ResponseUtil<>().setErrorMsg(UserRetCode.USERORPASSWORD_ERRROR.getMessage());
        }
        if (login.getToken() == null) {
            return new ResponseUtil<>().setErrorMsg(UserRetCode.USER_ISVERFIED_ERROR.getMessage());
        }
        Cookie cookie = CookieUtil.genCookie("access_token", login.getToken(), "/", 1024);
        response.addCookie(cookie);
        ResponseData<Object> responseData = new ResponseUtil<>().setData(login);
        responseData.setTimestamp(System.currentTimeMillis());


//        //-----------xd插入----------------
//        Cookie cookie=new Cookie("access_token",login.getToken());
//        response.addCookie(cookie);
        return responseData;
    }

    @GetMapping("login")
    public ResponseData login(HttpServletRequest request) {
        String token = request.getHeader("user_info");
        JSONObject jsonObject = JSON.parseObject(token);
        Long uid = Long.parseLong(jsonObject.get("uid").toString());
        UserDto userDto = iLoginService.verificationLogin(uid);
        ResponseData<Object> responseData = new ResponseUtil<>().setData(userDto);
        responseData.setTimestamp(System.currentTimeMillis());
        return responseData;
    }

    /**
     * 注册
     */
    @PostMapping("register")
    public ResponseData register(@RequestBody UserRegisterRequest registerRequest, HttpServletRequest request) {
        //1.验证验证码
        String uuid = CookieUtil.getCookieValue(request, "kaptcha_uuid");
        KaptchaCodeRequest kaptchaCodeRequest = new KaptchaCodeRequest();
        kaptchaCodeRequest.setUuid(uuid);
        kaptchaCodeRequest.setCode(registerRequest.getCaptcha());
        iKaptchaService.validateKaptchaCode(kaptchaCodeRequest);
        //2.插入数据
        /**
         * 返回2，插入数据出错
         * 返回1，用户名已存在或邮箱已存在
         * 返回0，注册成功
         */
        int code = iUserRegisterService.register(registerRequest);
        if (code == 2) {
            return new ResponseUtil<>().setErrorMsg(UserRetCode.USER_REGISTER_FAILED.getMessage());
        }
        if (code == 1) {
            return new ResponseUtil<>().setErrorMsg(UserRetCode.USERNAME_ALREADY_EXISTS.getMessage() + "或邮箱已存在");
        }
        return new ResponseUtil<>().setData(null);
    }
//        String userInfo = request.getHeader("user_info");          // 得到一组Json字符串    {"uid":1, "username":"zs"}
//        JSONObject object = JSON.parseObject(userInfo);       // 这个类继承了Map<String,Object>  所以结果是{"uid"=1,"username"="zs"}
//        Long uid=Long.parseLong(object.get("id").toString());
//
//          UserLoginResponse response= iLoginService.selectById(uid);
//        return new ResponseUtil().setData(response);

    @RequestMapping("verify")
    public void verify(UserVerifyRequest userVerifyRequest, HttpServletResponse response) throws IOException {
        int verify = iUserRegisterService.verify(userVerifyRequest);
        if (verify == 1) {
            response.getWriter().println("激活失败，系统错误，请联系管理员");
        }
        if (verify == 2) {
            response.getWriter().println("激活失败，数据错误，请联系管理员");
        }
        response.getWriter().println("激活成功,请重新登录");
    }

    @RequestMapping("loginOut")
    public ResponseData loginOut(HttpServletRequest request,HttpServletResponse response){
        //Cookie cookie1 = new Cookie("access_token",null);
//        Cookie[] cookies = request.getCookies();
        //response.addCookie(cookie1);
        //cookie1.setMaxAge(0);
        //Cookie[] cookies = request.getCookies();
        /*for (Cookie cookie : cookies) {
            if ("access_token".equals(cookie.getName())) {
                response.addCookie(cookie);
                cookie.setMaxAge(0);
                //cookie.setMaxAge(0);
                return new ResponseUtil<>().setData(null);
            }
        }*/
        Cookie cookie1 = new Cookie("access_token", null);
        cookie1.setMaxAge(0);
        cookie1.setPath("/");
        response.addCookie(cookie1);

//        Cookie cookie = CookieUtil.genCookie("access_token", null, "/", 0);
//        response.addCookie(cookie);

        return new ResponseUtil<>().setData(null);
    }
}
